package com.example.anpnovel.controller.crud;


import com.example.anpapi.entity.po.novelmodel.Category.Category;
import com.example.anpapi.entity.vo.R;
import com.example.anpnovel.service.interfaces.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分类添加
     * @param category
     * @return
     */
    @PostMapping("/save")
    public R<Category> save(@RequestBody Category category){
        log.info("分类添加:{}", category);
        categoryService.save(category);
        return R.success(category,"分类添加成功");
    }

    /**
     * 根据分类id删除分类
     * @param category
     * @return
     */
    @DeleteMapping("/remove")
    public R<String> remove(@RequestBody Category category){
        log.info("分类删除:{}", category);
        if(categoryService.getById(category.getId()) != null)
        {
            categoryService.removeById(category.getId());
            return R.success(null,"分类删除成功");
        }
        return R.error("未找到该分类");
    }

    /**
     * 根据分类id查找分类
     * @param id
     * @return
     */
    @GetMapping("/get")
    public R<Category> get(@RequestParam(value = "id") Long id) {
        log.info("查询分类的id为{}", id);
        Category category = categoryService.getById(id);
        return R.success(category, "查询分类成功");
    }

    /**
     * 根据父分类id查找所有子分类
     * @param parentId
     * @return
     */
    @GetMapping("/getByParentId")
    public R<List<Category>> getByParentId(@RequestParam(value = "parentId") Long parentId) {
        log.info("查询父分类id为{}的所有子分类", parentId);
        List<Category> categories = categoryService.lambdaQuery()
                .eq(Category::getParentId, parentId)
                .orderByAsc(Category::getSortOrder)
                .list();
        return R.success(categories, "查询分类成功");
    }

    /**
     * 查找所有启用的分类
     * @return
     */
    @GetMapping("/getActive")
    public R<List<Category>> getActive() {
        log.info("查询所有启用的分类");
        List<Category> categories = categoryService.lambdaQuery()
                .eq(Category::getIsActive, true)
                .orderByAsc(Category::getSortOrder)
                .list();
        return R.success(categories, "查询分类成功");
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PostMapping("/update")
    public R<Category> update(@RequestBody Category category){
        log.info("修改的分类为{}", category);
        categoryService.updateById(category);
        return R.success(category,"修改分类成功");
    }

}

